package co.gov.medellin.sdep.sisdep.model.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.object.MappingSqlQuery;
import org.springframework.jdbc.object.SqlUpdate;

import co.gov.medellin.sdep.sisdep.common.OracleHelper;
import co.gov.medellin.sdep.sisdep.model.Agenda;
import co.gov.medellin.sdep.sisdep.model.CentroComercial;

public class AgendaDAOImpl extends JdbcDaoSupport implements IAgendaDAO {

    private InsertOperation insertOperation;

    private UpdateOperation updateOperation;

    private DeleteOperation deleteOperation;

    private DeleteByPrimaryKey deleteByPrimaryKey;

    private FindByPrimaryKeyQuery findByPrimaryKeyQuery;

    private FindByCriteriaQuery findByCriteriaQuery;

    private FindAllQuery findAllQuery;

    private FindByActiveStateQuery findByActiveStateQuery;

	private static final String SELECT = "SELECT * FROM CCO_AGENDA_T ";
	private static final String WHERE = " WHERE ";
	private static final String PARAMETER = " ?, ";

    public void delete(Agenda agenda) {
		deleteOperation.execute( agenda  );
	}

	public void deleteByPrimaryKey(long id) {
		deleteByPrimaryKey.execute(id);
	}

	public Agenda findByPrimaryKey(long login) {
		return findByPrimaryKeyQuery.runQuery(login);
	}

	public void insert(Agenda agenda) {
		insertOperation.execute( agenda );
	}

	public void update(Agenda agenda) {
		updateOperation.execute( agenda );
	}

	public Agenda findByCriteria(Agenda  agenda) {
		return findByCriteriaQuery.runQuery(agenda);
	}

	public List load(Agenda agenda) {
		return findAllQuery.runQuery(agenda);
	}

	public Agenda findByActiveState(Agenda  agenda) {
		return findByActiveStateQuery.runQuery(agenda);
	}

	public void initDao() {
    	insertOperation   = new InsertOperation( getDataSource() );
    	updateOperation = new UpdateOperation(  getDataSource() );
    	//deleteOperation = new DeleteOperation(  getDataSource() );
    	//deleteByPrimaryKey = new DeleteByPrimaryKey( getDataSource());
    	//findByPrimaryKeyQuery   = new FindByPrimaryKeyQuery(  getDataSource() );
    	//findByCriteriaQuery = new FindByCriteriaQuery(  getDataSource() );
    	findAllQuery = new FindAllQuery( getDataSource() );
    	//findByActiveStateQuery = new FindByActiveStateQuery( getDataSource() );
    }

    // ------------- SaveOperation ---------------------------------------
	class InsertOperation extends SqlUpdate	{
		private static final String sql = "INSERT INTO CCO_AGENDA_T ("
				  + " ID, "
				  + " ID_CENTRO_COMERCIAL, "
				  + " FECHA_INICIO, "
				  + " FECHA_FIN, "
				  + " OBSERVACION, "
				  + " ESTADO, "
				  + " USUARIO_CREA, "
				  + " FECHA_CREA "
				  + ") VALUES ("
			  	  + " CCO_AGENDA_SEC.nextVal, "
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + PARAMETER
				  + "SYSDATE"
				  + ")";
		public  InsertOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.DATE));
			declareParameter( new SqlParameter(Types.DATE));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			compile();
		}
		public void execute(Agenda agenda) {
			InsertOperation.this.update( new Object[]{				
				agenda.getIdCentroComercial(),
				agenda.getFechaInicio(),
				agenda.getFechaFin(),
				agenda.getObservacion(),
				agenda.getEstado(),
				agenda.getUsuarioCrea()
				});
		}
    }

    // ------------- UpdateOperation -------------------------------------
    class UpdateOperation extends SqlUpdate	{
    	private static final String sql = "UPDATE CCO_AGENDA_T SET "					  
					  + " ID_CENTRO_COMERCIAL = ? ,"
					  + " FECHA_INICIO = ? ,"
					  + " FECHA_FIN = ? ,"
					  + " OBSERVACION = ? ,"
					  + " ESTADO = ? ,"
					  + " USUARIO_MODIFICA = ? ,"
					  + " FECHA_MODIFICA = SYSDATE"
				  	  + WHERE
				  	  + " ID = ? ";
		public  UpdateOperation(DataSource ds) {
			super(ds,sql);
			//set here required parameters			
			declareParameter( new SqlParameter(Types.INTEGER));
			declareParameter( new SqlParameter(Types.DATE));
			declareParameter( new SqlParameter(Types.DATE));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.CHAR));
			declareParameter( new SqlParameter(Types.INTEGER));
			compile();
		}
		public void execute(Agenda agenda) {
			UpdateOperation.this.update( new Object[]{						
				agenda.getIdCentroComercial(),
				agenda.getFechaInicio(),
				agenda.getFechaFin(),
				agenda.getObservacion(),
				agenda.getEstado(),
				agenda.getUsuarioModifica(),
				agenda.getId()
				});
		}
    }

    // ------------- DeleteOperation -------------------------------------
    class DeleteOperation extends SqlUpdate	{
		private static final String sql = "DELETE FROM CCO_AGENDA_T "
										+ WHERE +"1=1";
		public DeleteOperation(DataSource ds) {
			super(ds,sql);
			compile();
		}
		public void execute(Agenda agenda) {
			this.update( new Object[]{
			});
		}
	}

    // ------------- DeleteByPrimaryKey ----------------------------------
    class DeleteByPrimaryKey extends SqlUpdate	{
		private static final String sql = "DELETE FROM CCO_AGENDA_T "
										+ WHERE +"1=1";
		public DeleteByPrimaryKey(DataSource ds) {
			super(ds,sql);
			compile();
		}	
		public void execute(long id) {
			this.update( new Object[]{
			});
		}	
    }

    // ---- BaseQueryOperation for Mapping ResultSet values --------------
	abstract class BaseQueryOperation extends MappingSqlQuery {
		public BaseQueryOperation(DataSource ds,String sql) {
	   		super(ds,sql);
		}	
		protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
			Agenda agenda = new Agenda();
				agenda.setId(new Long(rs.getLong("ID")));
				agenda.setIdCentroComercial(new Long(rs.getLong("ID_CENTRO_COMERCIAL")));
				agenda.setIdCentroComercialStr(rs.getString("ID_CENTRO_COMERCIAL"));
				agenda.setFechaInicio(rs.getDate("FECHA_INICIO"));		
				agenda.setFechaFin(rs.getDate("FECHA_FIN"));		
				agenda.setObservacion(rs.getString("OBSERVACION"));
				agenda.setEstado(rs.getString("ESTADO"));
				agenda.setUsuarioCrea(rs.getString("USUARIO_CREA"));
				agenda.setFechaCrea(rs.getDate("FECHA_CREA"));		
				agenda.setUsuarioModifica(rs.getString("USUARIO_MODIFICA"));
				agenda.setFechaModifica(rs.getDate("FECHA_MODIFICA"));		
			return agenda;
		}
    }

    // ------------- FindByPrimaryKeyQuery -------------------------------
    class FindByPrimaryKeyQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE +"1=1";
    	public FindByPrimaryKeyQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public Agenda runQuery(long id) {
			List result =  execute( new Object[]{new Long(id)});
			if ( result.size() > 0 ) {
        		return (Agenda) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByCriteriaQuery ---------------------------------    
    class FindByCriteriaQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " 1=1 ";
			//For required criteria elements uncomment required values
			  	  	  					//+ " AND ID = ? "
			  	  	  					//+ " AND ID_CENTRO_COMERCIAL = ? "
			  	  	  					//+ " AND FECHA_INICIO = ? "
			  	  	  					//+ " AND FECHA_FIN = ? "
			  	  	  					//+ " AND OBSERVACION = ? "
			  	  	  					//+ " AND ESTADO = ? "
			  	  	  					//+ " AND USUARIO_CREA = ? "
			  	  	  					//+ " AND FECHA_CREA = ? "
			  	  	  					//+ " AND USUARIO_MODIFICA = ? "
			  	  	  					//+ " AND FECHA_MODIFICA = ? "
										//+ "";
    	public FindByCriteriaQuery(DataSource ds) {
    		super(ds,sql);
    		//For required criteria elements uncomment required values
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.INTEGER) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			//declareParameter( new SqlParameter(Types.CHAR) );
			//declareParameter( new SqlParameter(Types.DATE) );
			compile();
    	}
    	public Agenda runQuery(Agenda agenda) {
			List result =  execute( new Object[]{
			//For required criteria elements uncomment required values
				//agenda.getId(),
				//agenda.getIdCentroComercial(),
				//agenda.getFechaInicio(),
				//agenda.getFechaFin(),
				//agenda.getObservacion(),
				//agenda.getEstado(),
				//agenda.getUsuarioCrea(),
				//agenda.getFechaCrea(),
				//agenda.getUsuarioModifica(),
				//agenda.getFechaModifica(),
				});
			if ( result.size() > 0 ) {
        		return (Agenda) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindAllQuery ----------------------------------------    
    class FindAllQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE + " ID_CENTRO_COMERCIAL IN  "
										+ " (SELECT ID FROM CCO_CENTRO_COMERCIAL_T WHERE UPPER(NOMBRE) LIKE UPPER(?))";
    	public FindAllQuery(DataSource ds) {
    		super(ds,sql);
    		declareParameter( new SqlParameter(Types.CHAR) );
			compile();
    	}
    	public List runQuery(Agenda agenda) {
			List result =  execute( new Object[]{
					"%" + agenda.getStrCentroComercial() + "%"
			});
			if ( result.size() > 0 ) {
        		return  result;
        	} else {
        		return null;
        	}
    	}
    }

    // ------------- FindByActiveStateQuery  -----------------------------
    class FindByActiveStateQuery extends BaseQueryOperation {
		private static final String sql = SELECT
										+ WHERE +"1=1";
    	public FindByActiveStateQuery(DataSource ds) {
    		super(ds,sql);
			compile();
    	}
    	public Agenda runQuery(Agenda agenda) {
			List result =  execute( new Object[]{
			});
			if ( result.size() > 0 ) {
        		return (Agenda) result.get(0);
        	} else {
        		return null;
        	}
    	}
    }

    public List generatePDFAgenda(Agenda agenda) {
		
		StringBuffer query = new StringBuffer();
		ArrayList lista = new ArrayList();
	
		query.append("SELECT CCO.NOMBRE AS CENTRO_COMERCIAL, AG.FECHA_INICIO AS FECHA_I, AG.FECHA_FIN AS FECHA_f, ");
		query.append("AGA.ACTIVIDAD AS ACTIVIDAD, AGA.ORDEN AS ORDEN, MAE.VRT_NOMBRE AS TIPO_ACT, ");
		query.append("(P.PRIMER_NOMBRE || ' ' || P.SEGUNDO_NOMBRE || ' ' || P.PRIMER_APELLIDO || ' ' || P.SEGUNDO_APELLIDO) AS VINCULADO FROM ");
		query.append("CCO_AGENDA_T AG INNER JOIN ");
		query.append("CCO_CENTRO_COMERCIAL_T CCO ON AG.ID_CENTRO_COMERCIAL=CCO.ID INNER JOIN ");		
		query.append("CCO_AGENDA_ACTIVIDAD_T AGA ON AG.ID = AGA.ID_AGENDA INNER JOIN ");
		query.append("ADM_VALOR_TIPO_MAESTRA_T MAE ON AGA.ID_AGENDA_TIPO_ACTIVIDAD=MAE.ID_VALOR_TIPO LEFT JOIN ");		
		query.append("CCO_AGENDA_ACTIVIDAD_VINC_T AAV ON AGA.ID = AAV.ID_AGENDA_ACTIVIDAD LEFT JOIN ");
		query.append("ADM_PERSONA_T P ON AAV.ID_VINCULADO = P.ID ");
		query.append("WHERE AG.ID_CENTRO_COMERCIAL=? ");
		query.append("ORDER BY  FECHA_INICIO,ORDEN ");
		
		List params = new ArrayList();
		params.add(agenda.getIdCentroComercial());
		
		List rows = this.getJdbcTemplate().queryForList(query.toString(), params.toArray());
		
    	Iterator iterator = rows.iterator();
    	
    	while (iterator.hasNext()) {
    		Map agendaMap = (Map) iterator.next();
        	Agenda agendaReport = new Agenda();	
        	agendaReport.setStrCentroComercial(agendaMap.get("CENTRO_COMERCIAL").toString());
        	agendaReport.setStrFechaInicial(OracleHelper.timeStamp2string((Timestamp) agendaMap.get("FECHA_I")));
        	agendaReport.setStrFechaFinal(OracleHelper.timeStamp2string((Timestamp) agendaMap.get("FECHA_I")));
        	agendaReport.setStrActividad(agendaMap.get("ACTIVIDAD").toString());
        	agendaReport.setStrOrden(agendaMap.get("ORDEN").toString());
        	agendaReport.setStrTipoActividad(agendaMap.get("TIPO_ACT").toString());
        	agendaReport.setVinculado(agendaMap.get("VINCULADO").toString());
    		lista.add(agendaReport);
    	}
		
		return lista;
	}  
	    
}
